
package com.om.base;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.sql.*;
import java.time.LocalTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.format.annotation.DateTimeFormat;

import sun.swing.MenuItemLayoutHelper.ColumnAlignment;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.om.base.BeanFactory;
import com.om.base.ChildRelation;
import com.om.base.SqlFilter;
import com.om.base.Utils;
import com.om.common.CustomerExecption;
import com.om.common.MD5;
import com.om.common.TimeStampToInt;
import com.om.pages.PageInfo;
import com.sun.management.jmx.Trace;



/**   
* @CopyRright (c) 
* @Title:AbstractBean.java
* @Description: 数据库操作的基础类（里面集成了基本的增删改查的方法）
* @author tangchuan
* @CreateDate 2014-10-01   
* @version V1.0   
*/ 
public abstract class  AbstractBean<T> extends HashMap<String, Object> implements Serializable{
	
	
	
	public static final String DATA_ROW_STATE="_data_row_state";	
	public static final String KEY_VALUE="_key_value";
	/**
	 * 标示当前记录状态为未改变
	 */
	public static final String NO_CHANGE="1";
	/**
	 * 标示当前记录状态为删除
	 */
	public static final String DELETED="4";
	/**
	 * 标示当前记录状态为为新增
	 */
	public static final String NEW="2";
	/**
	 * 标示当前记录状态为修改
	 */
	public static final String EDIT="3";
	
	public boolean inited = false;
	
	public Map<String, Object> table = new HashMap<String, Object>();
	
	public Class LuceneIndexClass = null;
	/**
	 * 当前模型对应的数据库表的名称
	 */
	public String TABLE_NAME = "";
	/**
	 * 从表的关系集合，以键值对的形式保存于当前模型关联的从表关系
	 */
	public HashMap<String, ChildRelation>  childMap = new HashMap<String, ChildRelation>();
	
	/**
	 * 存放外间关联的关系列表，在调用loadForignData的时候会加载该列表中的数据
	 */
	public HashMap<String, ForignRelation> forignMap = new HashMap<String, ForignRelation>();
	
	/**
	 * 存放字段静态枚举的集合
	 */
	protected ArrayList<FieldEnum> enumList = new ArrayList<FieldEnum>();
	
	/**
	 * 存放在查询的时候需要格式化的时间字段列表
	 */
	protected ArrayList<TimeFieldFormat> timeList = new ArrayList<TimeFieldFormat>();
	
	
	
	/**
	 *表/视图的名称 
	 */
	public String PrimaryKey = "";
	
	public String PrimaryKeyField = "";
	/**
	 * 当前表的主键是否为自增长类型
	 */
	public boolean AutoIncrease = true;
	/**
	 * 当前对象的记录是否禁止删除
	 */
	public boolean deleteForbidden = false;
	
	/**
	 * 当前对象是否用内建的查询费方法进行查询
	 */
	public boolean queryByInnerMethod = false;
	
	
	
	/**
	 * 当前使用的数据库连接
	 */
	public Connection connection = null;
	/**
	 * 字段列表
	 */
	public String[] Field = new String[0];
	/**
	 * 对应字段列表的显示名称
	 */
	public String[] Titles = new String[0];
	
	/**
	 * 在修改的时候不允许被更在的字段列表
	 */
	public List<String>readonlyList = new ArrayList<String>();
	//public String[] readonlyFields =new String[0];
	/**
	 * 当前对象是否为只读（不允许执行保存）
	 */
	public boolean realonly = false;
	/**
	 * 当前对象的父对象关系（用于加载类似于树形结构的数据）
	 */
	public ParentRelation Parent = null;
	
	
	public AbstractBean parentNode= null;
	
	/**
	 * 当前表中的不能重复的字段列表
	 * 如果设置了改字段在调用保存到 时候会先对当前集合中字段的值逐一做唯一性验证
	 * 如果验证通过就继续保存动作，如果不通过会向调用方抛出异常
	 */
	public List<String>uniqueList = new ArrayList<String>();
	//public String []uniqueFields = new String[0];
	protected String columnConfig = "";
	/**
	 * 当前表中的非空的字段列表
	 * 如果设置了改字段在调用保存到 时候会先对当前集合中字段的值逐一做非空验证
	 * 如果验证通过就继续保存动作，如果不通过会向调用方抛出异常
	 */
	public List<String>requireList = new ArrayList<String>();
	
	//用于保存在派生类的generateQuerySql方法中定义的查询语句的模板
	protected String customerQuerySqlTemplate="";
	protected String customerQuerySql="";
	protected String defaultOrderByExpress="";
	protected int defaultPageSize=10;
	protected int defaultStartIndex=0;
	protected PreparedStatement batchPret = null;
	protected java.lang.reflect.Field[] declareFields;
	
	/**
	 * 以键值对的形式保存当前对象关联的从表（通过addChild方法添加的）对象的数据集合
	 * 其中键为从表对象的Class,值为与当前主表关联的从表记录的对象集合
	 */
	public HashMap<String, List<T>  > childrenData = new HashMap<String, List<T> >();
	
	public HashMap<String, T> forignData = new HashMap<String, T>();
	
	/**
	 * 调用update/insertItem前会先验证改字段是否为true
	 */
	protected boolean validate = false;
	
	public boolean usingLuceneQuery = false;
	
	public abstract boolean save() throws Exception;
	
	public String getDefaultOrderByExpress() {
		return defaultOrderByExpress;
	}

	public void setDefaultOrderByExpress(String defaultOrderByExpress) {
		this.defaultOrderByExpress = defaultOrderByExpress;
	}

	public int getDefaultPageSize() {
		return defaultPageSize;
	}

	public void setDefaultPageSize(int defaultPageSize) {
		this.defaultPageSize = defaultPageSize;
	}

	public int getDefaultStartIndex() {
		
		return defaultStartIndex;
	}

	public void setDefaultStartIndex(int defaultStartIndex) {
		this.defaultStartIndex = defaultStartIndex;
	}
	
	public void init() throws Exception{
		if(!this.inited){
			//初始化表名称
			initTableName();
			//初始化主键字段
			initPrimaryKey();
			
			//初始化自定义的各种信息
			initDeclareColumns();
			
			//初始化字段列表
			initColumns();
			
			this.inited = true;
		}
		
	}
	/**
	 * 返回当前对象的记录条数（改方法主要用于在派生类中进行重载）
	 * @return 当前对象对应表的所有记录条数
	 */
	public int getRecordCount() {
		int count = 0;

		return count;
	}
	
	public List<AbstractBean>proceedQueue = null;
	
	/**
	 * 获取当与前对象关联的所有字表的数据
	 * @return  获取当与前对象关联的所有字表的数据
	 */
	
	public HashMap<String,List<T>> getChildrenData() {
		return childrenData;
	}
	
	/**
	 * 处理链表中的平行关系的数据
	 * @param chain 包含平行关系的数据链表
	 * @throws Exception
	 */
	public static void ChainProceed(List<AbstractBean> chain) throws Exception{
		List<AbstractBean>proceedQueue = new ArrayList<AbstractBean>();
		AbstractBean header = null;
		for(int i=0;i<chain.size();i++){
			AbstractBean bean = chain.get(i);
			Chain config = bean.getClass().getAnnotation(Chain.class);
			if(config == null ){
				throw new CustomerExecption("-101", bean.getClass().getName()+": Chain must be config!");
			}
		}
		if(header == null){
			throw new CustomerExecption("-102","Header of chain must be set!");
		}
		header.proceedQueue = proceedQueue;
		proceed(chain,header);
		
	}
	
	/**
	 * 处理链表中的一条数据
	 * @param chain 包含平行关系的数据链表
	 * @param chainNode 当前被处理的节点
	 * @throws Exception
	 */
	protected static void proceed(List<AbstractBean> chain,AbstractBean chainNode) throws Exception {
		Chain config = chainNode.getClass().getAnnotation(Chain.class);
		
		String methodName = config.chainMehod();
		if (methodName == null || "".equals(methodName)) {
			methodName = "save";
		}
		Method method = chainNode.getClass().getMethod(methodName, null);
		method.setAccessible(true);
		method.invoke(chainNode, null);
		
		chainNode.proceedQueue.add(chainNode);
		Class clazz = config.nextClass();
		for (int i = 0; i < chain.size(); i++) {
			AbstractBean node = chain.get(i);
			if (node.getClass().equals(clazz)) {
				node.proceedQueue = chainNode.proceedQueue;
				chain.remove(i);
				proceed(chain, node);
				break;
			}
		}
	}
	
	public static  AbstractBean CopyConfig(AbstractBean from,AbstractBean target ){		
		target.Field             =  from.Field;
		target.TABLE_NAME        =  from.TABLE_NAME;
		target.PrimaryKey        =  from.PrimaryKey;
		target.PrimaryKeyField   = 	from.PrimaryKeyField;
		target.requireList       =  from.requireList;
		target.uniqueList        =  from.uniqueList;
		target.readonlyList      =  from.readonlyList;
		target.childMap          =  from.childMap;
		target.forignMap         =  from.forignMap;
		target.AutoIncrease      =  from.AutoIncrease;
		target.deleteForbidden   = 	from.deleteForbidden;
		target.queryByInnerMethod=  from.queryByInnerMethod;
		target.usingLuceneQuery  = 	from.usingLuceneQuery;
		return target;
	}
	
	/**
	 * 设置当与前对象关联的所有字表的数据
	 * @param childrenData 需要设置的子表对象集合
	 */
	public void setChildrenData(HashMap<String, List<T>> childrenData) {
		this.childrenData = childrenData;
	}
	
	/**对指定表的某个字段做唯一性验证
	 * @param className 需要检查的对象的Classname
	 * @param chkField 需要检查的字段名称
	 * @param chkValue 需要检查的字段的值
	 * @param pkValue 需要验证的记录的主键值
	 * @return 成功返回true否则返回false
	 */
	public static boolean UniqueValidate(String className, String chkField, Object chkValue, Object pkValue) {
	    boolean unique = true;
        try {
        	
	    	AbstractBean  bean = AbstractBean.getInstance(className+"");
            if (pkValue == null || "".equals(pkValue)) {
            	pkValue = - 1;
            }
            
            bean.connection = Utils.GetOpenedConnection();
            if(bean.loadItem(chkField, chkValue)){
            	if(!bean.getStringValue(bean.PrimaryKey).equals(pkValue.toString())){
            		unique = false;
            	}
            }
            
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        return unique;
        
  }

	/**对指定表的某个字段做唯一性验证
	 * @param cls 需要检查的模型的类
	 * @param chkField 需要检查的字段名称
	 * @param chkValue 需要检查的字段的值
	 * @param pkValue 需要验证的记录的主键值
	 * @return 成功返回true否则返回false
	 */
	public static boolean UniqueValidate(Class cls, String chkField, Object chkValue, Object pkValue) {
	    return  AbstractBean.UniqueValidate(cls.getName(), chkField, chkValue, pkValue);
        
    } 
	
	/**
	 * 对指定表的某个字段做唯一性验证
	 * @param className 需要检查的对象的Classname
	 * @param filter
	 * @return
	 */
	public static boolean UniqueValidate(String className,  SqlFilter filter) {
	    boolean unique = true;
        try {
        	
	    	AbstractBean  bean = AbstractBean.getInstance(className);
                        
            bean.connection = Utils.GetOpenedConnection();
            if(bean.loadFirst(filter)){
            	unique = false;
            }
            
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        return unique;
        
   }
	
	/**
	 * 
	 * @param cls
	 * @param filter
	 * @return
	 */
	public static boolean UniqueValidate(Class cls,  SqlFilter filter) {
		return  AbstractBean.UniqueValidate(cls.getName(), filter);
    }
	
	
	/**
	 * 对于指定模型获取符合某个过滤条件的记录集合
	 * @param filter 带有过滤条件的SqlFilter对象
	 * @param beanClass  需要查询的模型的Class
	 * @param con  数据连接对象
	 * @return 符合filter过滤条件的记录总数
	 */
	public static int GetRecordCount(SqlFilter filter, Class beanClass,Connection con) {
		int count = 0;
		String sql = "";
		try {
			if (filter == null) {
				filter = new SqlFilter();
			}
			if (con != null) {
				String className = beanClass.getName();
				AbstractBean bean = (AbstractBean) Class.forName(className)
						.newInstance();
				sql = bean.generateCountSql();
				Object obj = BeanFactory.ExecuteQuery(sql, filter, bean, con);
				if (obj != null) {
					count = Integer.valueOf(obj.toString()).intValue();
			
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return count;
	}
	
	/**
	 * 对于指定模型获取符合某个过滤条件的记录集合
	 * @param filter 带有过滤条件的SqlFilter对象
	 * @param beanClass  需要查询的模型的Class
	 * @return 符合filter过滤条件的记录总数
	 */
	public static int GetRecordCount(Class beanClass, SqlFilter filter) {
		int count = 0;
		Connection con = null;
		try {
			con = Utils.GetOpenedConnection();
			count = GetRecordCount(filter, beanClass, con);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return count;
	}

	
	

	/**
	 * 根据uniqueFields中设置的需要进行非空验证的字段列表进行非空验证
	 * @return 返回验证失败的字段
	 */
	public String uniqueCheck() {
		this.validate = false;
		for (int i = 0; i < this.uniqueList.size(); i++) {
			String field = this.uniqueList.get(i);
			if (!AbstractBean.UniqueValidate(this.getClassName(), field,
				get(field), getKeyValue())) {		
				return field;
			}
		}
		
		this.validate = true;
		return "";
	}
	
	/**
	 * 根据mustFields中设置的需要进行非空验证的字段列表进行非空验证
	 * @return 返回验证失败的字段
	 */
	public String emptyCheck() {
		for ( int i = 0; i < this.requireList.size(); i++) {
			String field = this.requireList.get(i);
			Object value = this.get(field);
			if (!(value!=null  && !value.equals(null) && !"".equals(value))) {
				return field;
			}
		}
		return "";
	}

	/**
	 * 返回当前对象中主键字段的值
	 * @return 主键对象的值
	 */
	public Object getKeyValue(){
		return this.get(this.PrimaryKey);
	}
	  
	  
	
	/**
	 * 此方法被框架自动调用，可以再派生类中进行重载，不需要进行显式调用
	 * 当前对象生成查询语句的方法，默认为select * from [表名称]，可根据需要自行在派生类中进行重载
	 * @return 当前对象的数据查询语句
	 * @throws Exception 
	 */
	public String generateQuerySql() throws Exception {
		this.initTableName();
		this.initPrimaryKey();
		String sql = "select * from " + this.TABLE_NAME;
		return sql;
	}
	
	/**
	 * 此方法被框架自动调用，可以再派生类中进行重载，不需要进行显式调用
	 * 生成以SqlFilter为查询条件的当前的查询语句
	 * @param filter  带有查询条件的集合
	 * @return 针对于前对象关联的表生成以filter为过滤条件的查询语句
	 * @throws Exception 
	 */
	public String generateQuerySql(SqlFilter filter) throws Exception {
		String sql = generateQuerySql() ;
		sql =generateQuerySql(sql,filter);
		return sql;
	}
	
	/**
	 * 此方法被框架自动调用，可以再派生类中进行重载，不需要进行显式调用
	 * 生成以SqlFilter为查询条件的当前的查询语句
	 * @param sql
	 * @param filter
	 * @return  带条件的当前对象的数据查询语句
	 */
	public String generateQuerySql(String sql,SqlFilter filter) {
		this.customerQuerySqlTemplate =sql;
		if (filter != null ) {
			this.initColumns();
			//filter.getFilterExpress();
			String strOrder  ="";
			Pattern pattern =Pattern.compile("order\\s+by.*(asc|desc)?");
			if(this.defaultOrderByExpress!=null && !"".equals(this.defaultOrderByExpress)){
				Matcher m0 = pattern.matcher(this.defaultOrderByExpress);
				if(m0.find()){
					strOrder =  m0.group();
					//strOrder =strOrder.replaceAll("order\\s+by", "");
				}
			}
			else {
				Matcher m0 = pattern.matcher(sql);
				if(m0.find()){
					strOrder =  m0.group();
					strOrder =strOrder.replaceAll("order\\s+by", "");
				}
			}
			
			if (LuceneUtils.IndexExist(this.LuceneIndexClass)) {
				LuceneUtils lu = new LuceneUtils(this.LuceneIndexClass);
				lu.setStartIndex(this.defaultStartIndex);
				filter = lu.getFilter(filter,strOrder,this.defaultPageSize);
				this.usingLuceneQuery = lu.usingLuceneQuery;
			}
			String strExpress  = filter.getFilterExpress();
			
			Pattern p = Pattern.compile("(\\$|@)\\{\\w+\\}");
			Matcher m = p.matcher(sql);
			if(m.find() && sql.indexOf("${where}")==-1){
				/**
				 *自己手动重载了generateQuerySql且其中已经带有了where和各种参数占位符
				 *按照Sql语句中占位符的顺序对SqlFilter立面的各项做调整 
				 */
				String field = m.group(); 
				String field1 = field.replaceAll("(\\$|@)", "").replace("}", "").replace("{", "");
				String value = filter.getValue(field1).toString();
				sql = sql.replaceAll("\\$\\{"+field1+"\\}" , value);
				while(m.find()){
					field = m.group(); 
					field1 = field.replaceAll("(\\$|@)", "").replace("}", "").replace("{", "");
					value = filter.getValue(field1).toString();
					sql = sql.replaceAll("\\$\\{"+field1+"\\}" , value);
				}
				filter.removeAll();
			}
			else if(sql.indexOf("${where}")==-1 &&  sql.indexOf("CALL")==-1 && !"".equals(strExpress)){//调用存储过程或者是带了${where}占位符
				String spit =sql.indexOf("where")==-1?" where ":" and "; 
				sql = sql + spit + strExpress;
			}
			else //默认的情况
			{
				if(!"".equals(strExpress)){
					sql = sql.replace("${where}", " where " + strExpress);
				}
				else{
					sql = sql.replace("${where}", " " );
				}
				
			}
		}
		this.customerQuerySql =sql;
		return sql;
	}
	
	public String generateQuerySql(String sql,SqlFilter filter,boolean usingLuceneQuery) {
		this.customerQuerySqlTemplate =sql;
		if (filter != null ) {
			this.initColumns();
			//filter.getFilterExpress();
			String strOrder  ="";
			Pattern pattern =Pattern.compile("order\\s+by.*(asc|desc)?");
			if(this.defaultOrderByExpress!=null && !"".equals(this.defaultOrderByExpress)){
				Matcher m0 = pattern.matcher(this.defaultOrderByExpress);
				if(m0.find()){
					strOrder =  m0.group();
					strOrder =strOrder.replaceAll("order\\s+by", "");
				}
			}
			else {
				Matcher m0 = pattern.matcher(sql);
				if(m0.find()){
					strOrder =  m0.group();
					strOrder =strOrder.replaceAll("order\\s+by", "");
				}
			}
			
			if (LuceneUtils.IndexExist(this.LuceneIndexClass) && usingLuceneQuery) {
				LuceneUtils lu = new LuceneUtils(this.LuceneIndexClass);
				lu.setStartIndex(this.defaultStartIndex);
				filter = lu.getFilter(filter,strOrder,this.defaultPageSize);
				this.usingLuceneQuery = lu.usingLuceneQuery;
			}
			String strExpress  = filter.getFilterExpress();
			
			Pattern p = Pattern.compile("(\\$|@)\\{\\w+\\}");
			Matcher m = p.matcher(sql);
			if(m.find() && sql.indexOf("${where}")==-1){
				/**
				 *自己手动重载了generateQuerySql且其中已经带有了where和各种参数占位符
				 *按照Sql语句中占位符的顺序对SqlFilter立面的各项做调整 
				 */
				String field = m.group(); 
				String field1 = field.replaceAll("(\\$|@)", "").replace("}", "").replace("{", "");
				String value = filter.getValue(field1).toString();
				sql = sql.replaceAll("\\$\\{"+field1+"\\}" , value);
				while(m.find()){
					field = m.group(); 
					field1 = field.replaceAll("(\\$|@)", "").replace("}", "").replace("{", "");
					value = filter.getValue(field1).toString();
					sql = sql.replaceAll("\\$\\{"+field1+"\\}" , value);
				}
				filter.removeAll();
			}
			else if(sql.indexOf("${where}")==-1 &&  sql.indexOf("CALL")==-1 && !"".equals(strExpress)){//调用存储过程或者是带了${where}占位符
				String spit =sql.indexOf("where")==-1?" where ":" and "; 
				sql = sql + spit + strExpress;
			}
			else //默认的情况
			{
				if(!"".equals(strExpress)){
					sql = sql.replace("${where}", " where " + strExpress);
				}
				else{
					sql = sql.replace("${where}", " " );
				}
				
			}
		}
		this.customerQuerySql =sql;
		return sql;
	}
	
	
	/**
	 * 返回一条空查询语句（主要用于初始化当当前对象所在类的数据库字段信息）
	 * @return 一条空查询语句
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	protected String getEmptySql() throws Exception {
		this.initTableName();
		this.initPrimaryKey();
		return "select * from "+this.TABLE_NAME+" where 1=0";
	}
	
	/**
	 * 返回一条当前对象的查询所有记录条数的sql语句，该语句被框架自动调用（可在派生类中进行重载）
	 * @return 返回一条当前对象的查询所有记录条数的sql语句
	 * @throws Exception 
	 */
	public String generateCountSql() throws Exception {
		this.initTableName();
		this.initPrimaryKey();
		String sql = "select count("+this.PrimaryKey+") from " + this.TABLE_NAME;
		return sql;
	}
	public String generateCountSql(SqlFilter filter) throws Exception {

		String sql = generateCountSql();
		if (filter != null ) {
			
			Pattern p1 = Pattern.compile("(\\$|@)\\{\\w+\\}");
			if("".equals(this.customerQuerySqlTemplate)){
				SqlFilter filterClone = filter.clone();
				this.generateQuerySql(filterClone);
			}
			Matcher m1 = p1.matcher(this.customerQuerySqlTemplate);
			if(m1.find() && this.customerQuerySqlTemplate.indexOf("${where}")==-1){
				SqlFilter ftClone =filter.clone();
				this.generateQuerySql(ftClone);
				return "select count(*)  as row_num from ( "+this.customerQuerySqlTemplate+" ) a ";
			}
			/*else{
				generateQuerySql(filter);
			}*/
			
			if(LuceneUtils.IndexExist(this.LuceneIndexClass)){
				LuceneUtils lu = new LuceneUtils(this.LuceneIndexClass);
				filter = lu.getFilter(filter);
			}
			
			this.initColumns();
			filter.getFilterExpress();
			List<String> fieldList = filter.getFieldList();
			for (int i = 0; i < fieldList.size(); i++) {
				String field = fieldList.get(i);
				Pattern p = Pattern.compile("(\\^\\d+)");
				Matcher m = p.matcher(field);
				if (m.find()) {
					field = m.replaceAll("");
				}
				if (!this.containsColumn(field) && !this.TABLE_NAME.equals("")) {
					//filter.remove(fieldList.get(i));
				}
			}
			String strExpress = filter.getFilterExpress();
			
			if (!(strExpress.equals(""))) {
				if(sql.indexOf("${where}")==-1 &&  sql.indexOf("CALL")==-1){
					sql = sql + " where " + strExpress;
				}
				else {
					sql = sql.replace("${where}", " where " + strExpress);
				}
				
			}
			else {
				sql = sql.replace("${where}","");
			}
				
			
		}
		return sql;
	}
	
	/**
	 * 根据指定的类名称返回一个对象的实例
	 * @param className 需要给定的对象的类
	 * @return 一个初始化过的实例
	 */
	public static AbstractBean getInstance(String className) {
		AbstractBean bean = null;
		try {
			bean = (AbstractBean) Class.forName(className).newInstance();
			bean.initColumns();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;
	}
	
	/**
	 * 根据指定的类名称返回一个对象的实例并通过主键加载数据库相关的值
	 * @param className  需要给定的对象的类
	 * @param key 主键值
	 * @return className的一个实例
	 */
	public static AbstractBean getInstance(String className,Object key) {
		AbstractBean bean = null;
		try {
			bean = (AbstractBean) Class.forName(className).newInstance();
			bean.initColumns();
			bean.loadItem(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;
	}
	
	/**
	 * 判断当前对象是否为新增对象
	 * @return 是返回true否返回false
	 */
	public Boolean isNew() {
		Boolean isnew = Boolean.valueOf(false);
		//Object id = get(this.PrimaryKey);
		Object id = this.getKeyValue();
		
		if ((id != null) && (!("null".equals(id))) && (!("".equals(id)))) {
			isnew = Boolean.valueOf(false);
		} else {
			isnew = Boolean.valueOf(true);
		}
		return isnew;
	}
	
	/**
	 * 判断当前对象中是否包含某个字段
	 * @param col 需要判断的字段名称
	 * @return 包含返回true否则返回false
	 */
	public Boolean containsColumn(String col) {
		boolean contains = false;
		if (getFieldIndex(col) > -1) {
			contains = true;
		}
		return Boolean.valueOf(contains);
	}
	
	/**
	 * 得到当前对象的字段总数
	 * @return 得到当前对象的字段总数
	 */
	public int getFieldCount() {
		return this.Field.length;
	}
	
	
	public int getFieldNameCount() {
		return this.Titles.length;
	}

	public String getTableName() {
		return this.TABLE_NAME;
	}

	public String getClassName() {
		String classname = super.getClass().toString()
				.replaceFirst("class", "").trim();
		return classname;
	}
	
	/**
	 * 初始化各种类型字段
	 * 1、非空字段
	 * 2、唯一字段
	 * 3、只读字段
	 * 4、数据库字段
	 * 5、外键关联关系
	 * 6、主从表关系
	 * @throws Exception 
	 */
	public void initDeclareColumns() throws Exception {
		if(this.declareFields == null){
			this.declareFields =this.getClass().getDeclaredFields();
		}
		if(declareFields!=null){
			
			for(int i=0;i<declareFields.length;i++){
				java.lang.reflect.Field field = declareFields[i];
				field.setAccessible(true);
				//主从表
				One2many o2m = field.getAnnotation(One2many.class);
				if(o2m != null ) {
					String localVariable =field.getName();	
					
					this.addChild(o2m.parentColumn()
								, o2m.childColumn()
								, o2m.childClass()
								, o2m.autoLoad()
								, o2m.deleteEnable()
								, localVariable);
				}
				
				//外键关联表
				Many2one m2o = field.getAnnotation(Many2one.class);
				if(m2o != null){
					String localVariable =field.getName();
					this.addForignRelation( m2o.localColumn(), 
											m2o.foreignColumn(), 
											m2o.forignClass(),
											m2o.loadChild(),
											m2o.autoLoad(),
											localVariable );
				}
				
				//日期格式字段
				DateTimeDisplay dateTimeDisplay =  field.getAnnotation(DateTimeDisplay.class);
				if(dateTimeDisplay!=null){
					TimeFieldFormat df = new TimeFieldFormat (dateTimeDisplay.field()
							,dateTimeDisplay.fromFormat()
							,dateTimeDisplay.targetFormat()
							,field.getName());
					this.timeList.add(df);
				}
				
				//非空字段
				Field column=  field.getAnnotation(Field.class);
				if (column == null )
					continue;
				
				if(column.required() && !requireList.contains(column.name())){
					requireList.add(column.name());
				}
				//唯一字段
				if(column.unique() && !uniqueList.contains(column.name())){
					uniqueList.add(column.name());
				}
				//只读字段
				if(column.readOnly() && !readonlyList.contains(column.name())){
					readonlyList.add(column.name());
				}
				
				
				
			}
		}
	}
	
	/**
	 * 初始化各种类型字段
	 * 1、非空字段
	 * 2、唯一字段
	 * 3、只读字段
	 * 4、数据库字段
	 */
	public void initColumns() {

		try {
			Connection con = null;
			
			if (this.Field.length != 0)
				return;

			String tableName = this.TABLE_NAME;
			if ("".equals(tableName)) {
				tableName = MD5.MD5Encode(this.generateQuerySql());
			}
			if (BeanFactory.TableColumnDirectory.containsKey(tableName)) {
				String[] columns = (String[]) BeanFactory.TableColumnDirectory.get(this.TABLE_NAME);
				this.Field = new String[columns.length];

				for (int i = 0; i < columns.length; ++i) {
					this.Field[i] = columns[i];
				}
				return;
			}

			if (this.connection == null) {
				con = Utils.GetOpenedConnection();
			} else {
				con = this.connection;
			}
			BeanFactory.GenerateFactory(this, con);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 设置对象中某个字段的值
	 * @param name  需要设置的字段
	 * @param value 需要设置的值
	 */
	public void set(String name, Object value) {
		try {
			if (value == null || "null".equals(value)){
				value="";
			}
			this.put(name, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 通过下标获取对象中的一个值
	 * @param i 字段下标
	 * @return 下标对应字段的值
	 */
	public Object get(int i) {
		try {
			String field = this.Field[i];
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 通过字段名获取一个值
	 * @param name 字段的名称
	 * @return 字段对应的值（如果字段不存在则返回null）
	 */
	public Object get(String name) {
		try {
			return super.get(name);
		} catch (Exception e) {
			System.out.println(e.getMessage() + "\r\n" + e.getStackTrace());
		}
		return null;
	}
	
	/**
	 * 以递归的方式获取以.进行分割的字段的值，比如col1.col2 col2包含在col1的对象中
	 * @param map 
	 * @param field
	 * @param pos
	 * @return
	 */
	private Object recursionGetValue(Map map, String field,int pos ){
		if(map == null  || map.size()==0){
			return null;
		}
		String  arr[] = field.split("\\.");
		if(pos<arr.length-1){
			String subName = arr[pos];
			
			return this.recursionGetValue((Map)map.get(subName),field , pos+1);
		}
		else{
			return map.get(arr[pos]);
		}
		
	}
	
	/**
	 * 通过字段名名称返回对应的字符串格式的值，如果字段值为空或者检索的字段不存在则返回空字符串
	 * @param name 需要检索的字段名称
	 * @return 通过字段名名称返回对应的字符串格式的值，如果字段值为空或者检索的字段不存在则返回空字符串
	 */
	public String getStringValue(String name) {
		String strValue = "";
		Object value = get(name);
		if ((value != null) && (!("null".equals(value)))) {
			strValue = value + "";
		}
		return strValue;
	}

	public void setEmpty(String field) {
		this.put(field, "");
	}

	public void clear() {
		super.clear();
	}

	public String getFieldName(int i) {
		try {
			return this.Titles[i];
		} catch (Exception e) {
			System.out.println(e.getMessage() + "\r\n" + e.getStackTrace());
		}
		return "";
	}
	
	/**
	 * 通过下标获取对象中字段名称
	 * @param i 字段下标
	 * @return 如果存在返回字段名否则返回null
	 */
	public String getField(int i) {
		try {
			return this.Field[i];
		} catch (Exception e) {
			System.out.println(e.getMessage() + "\r\n" + e.getStackTrace());
		}
		return null;
	}
	
	/**
	 * 返回指定字段在对象字段列表中的下标
	 * @param str 需要检索的字段名
	 * @return 如果存在则返回字段对应的下标，否则返回-1
	 */
	public int getFieldIndex(String str) {
		for (int i = 0; i < this.Field.length; ++i) {
			if (this.Field[i].equals(str)) {
				return i;
			}
		}
		return -1;
	}
	
	/**
	 * 添加需要进行格式化的日期字段
	 * @param field 数据库字段名称
	 * @param displayField 用来显示的字段，可与field不一致
	 * @param formate 日期的格式化字符串，比如yyyy-MM-dd
	 */
	/*protected void addTimeField(String field,String displayField,String formate){
		TimeFieldFormat  item = new TimeFieldFormat();
		item.setField(field);
		item.setDisplayField(displayField);
		item.setFormate(formate);
		this.timeList.add(item);
	}*/
	
/*	protected void addFieldEnum(String field,String displayField,HashMap<Object,String> map){
		FieldEnum e = new FieldEnum();
		e.setField(field);
		e.setDisplayField(displayField);;
		e.setMap(map);
		this.enumList.add(e);
	}
	
	protected void addFieldEnum(String field,String displayField,JSONObject obj){
	
		if(obj!=null){
			HashMap map = new HashMap();
			Object[] keys= obj.keySet().toArray();
			for(int i=0;i<keys.length;i++){
				map.put(keys[i], obj.get(keys[i]));
			}
			FieldEnum e = new FieldEnum();
			e.setField(field);
			e.setDisplayField(displayField);;
			e.setMap(map);
			this.enumList.add(e);
		}
	}
	
	
	protected void addFieldEnum(String field,String displayField,Object[] values,String[] text ){
		if(values.length == text.length){
			HashMap map = new HashMap();
			
			for(int i=0;i<values.length;i++){
				map.put(values[i], text[i]);
			}
			FieldEnum e = new FieldEnum();
			e.setField(field);
			e.setDisplayField(displayField);;
			e.setMap(map);
			this.enumList.add(e);
		}
	}*/
	
	
	/**
	 * 添加一条字表的关联关系，一个对象可以添加多条子关系，这些关联关系用于级联的查询、删除等操作
	 * @param relation 主从的关联关系
	 */
	public void addChild(ChildRelation relation) {
		this.childMap.put(relation.childClass.getName(), relation);
	}
	
	
	/**
	 * 添加一条外键关联关系
	 * @param relation 外键关联关系
	 */
	public void addForignRelation(ForignRelation relation) {
		this.forignMap.put(relation.forignClass.getName(), relation);
	}
	
	/**
	 * 添加一条外键关联关系
	 * @param localColumn 当前模型所在表的字段
	 * @param forignColumn 外键关联表的字段
	 * @param forignClass 外键关联的模型Class
	 * @param loadChild 是否加载外键关联模型的子表数据
	 */
	public void addForignRelation(String localColumn, String forignColumn,
			Class forignClass, boolean loadChild) {
		ForignRelation relation = new ForignRelation();
		relation.foreignColumn = forignColumn;
		relation.localColumn = localColumn;
		relation.forignClass = forignClass;
		relation.loadChild = loadChild;
		this.forignMap.put(relation.forignClass.getName(), relation);
	}
	
	/**
	 * 添加一条外键关联关系
	 * @param localColumn 当前模型所在表的字段
	 * @param forignColumn 外键关联表的字段
	 * @param forignClass 外键关联的模型Class
	 * @param loadChild 是否加载外键关联模型的子表数据
	 * @param displayKey 外键关联对象加载后存在于当前对象中的Key
	 * @param autoLoad 是否在当前对象加载的时候自动加载该关联对象
	 */
	public void addForignRelation(String localColumn, String forignColumn,
			Class forignClass, boolean loadChild,String displayKey, boolean autoLoad) {
		ForignRelation relation = new ForignRelation();
		relation.foreignColumn = forignColumn;
		relation.localColumn = localColumn;
		relation.forignClass = forignClass;
		relation.loadChild = loadChild;
		relation.autoLoad = autoLoad;
		relation.displayKey = displayKey;
		this.forignMap.put(relation.forignClass.getName(), relation);
	}
	
	public void addForignRelation(String localColumn, String forignColumn,
			Class forignClass, boolean loadChild,boolean autoLoad,String localVariableName) {
		ForignRelation relation = new ForignRelation();
		relation.foreignColumn = forignColumn;
		relation.localColumn = localColumn;
		relation.forignClass = forignClass;
		relation.loadChild = loadChild;
		relation.autoLoad = autoLoad;
		relation.localVariableName = localVariableName;
		this.forignMap.put(relation.forignClass.getName(), relation);
	}
	
	
	/**
	 * 添加一条字表的关联关系，一个对象可以添加多条子关系，这些关联关系用于级联的查询、删除等操作
	 * @param relation 主从的关联关系
	 */
	public void addChild(AbstractBean bean) {
		String className = bean.getClass().getSimpleName();
		
		List<T> beanList = new ArrayList<T>();
		if(this.childMap.containsKey(bean.getClass().getName())){
		
			if(this.childrenData.containsKey(className)){
				beanList =this.getChild(bean.getClass());
			}
			bean.set(AbstractBean.DATA_ROW_STATE, AbstractBean.EDIT);
			beanList.add((T) bean);
			this.childrenData.put(className, beanList);
			
		}
		this.set("childrenData", this.childrenData);
	}
	
	/**
	 * 添加一条字表的关联关系，一个对象可以添加多条子关系，这些关联关系用于级联的查询、删除等操作
	 * @param relation 主从的关联关系
	 */
	public void addChild(String childName,AbstractBean bean) {
		
		List<T> beanList = new ArrayList<T>();
		if(this.childrenData.containsKey(childName)){
			beanList = this.childrenData.get(childName);			
		}
		bean.set(AbstractBean.DATA_ROW_STATE, AbstractBean.EDIT);
		beanList.add((T) bean);
		this.childrenData.put(childName, beanList);
		this.set("childrenData", this.childrenData);
	}
	
	
	/**
	 * 添加一条字表的关联关系，一个对象可以添加多条子关系，这些关联关系用于级联的查询、删除等操作
	 * @param relation 主从的关联关系
	 */
	public void addChild(AbstractBean bean,boolean loadData) {
		if(this.childMap.containsKey(bean.getClass().getName())){
			List<T> beanList = new ArrayList<T>();
			bean.set(AbstractBean.DATA_ROW_STATE, AbstractBean.EDIT);
			beanList.add((T) bean);
			this.childrenData.put(bean.getClass().getSimpleName(), beanList);
		}
	}
	
	
	/**
	 * 添加一条字表的关联关系，一个对象可以添加多条子关系，这些关联关系用于级联的查询、删除等操作
	 * @param localColumn 当前对象中的关联字段
	 * @param foreignColumn 子对象对象中的关联字段
	 * @param childClass 子对象的类
	 */
	public void addChild(String localColumn, String foreignColumn,Class childClass) {
		ChildRelation relation = new ChildRelation();
		relation.localColumn = localColumn;
		relation.foreignColumn = foreignColumn;
		relation.childClass = childClass;
		this.childMap.put(childClass.getName(), relation);
	}
	
	/**
	 * 添加一条字表的关联关系，一个对象可以添加多条子关系，这些关联关系用于级联的查询、删除等操作
	 * @param localColumn 当前对象中的关联字段
	 * @param foreignColumn 子对象对象中的关联字段
	 * @param childClass 子对象的类
	 * @param autoLoad 该字表对象是否在当前记录调用loadAllChild的时候加载的时候自动加载
	 */
	public void addChild(String localColumn, String foreignColumn,Class childClass,boolean autoLoad) {
		ChildRelation relation = new ChildRelation();
		relation.localColumn = localColumn;
		relation.foreignColumn = foreignColumn;
		relation.childClass = childClass;
		relation.autoLoad = autoLoad;
		this.childMap.put(childClass.getName(), relation);
	}
	
	public void addChild(String localColumn, String foreignColumn,Class childClass,boolean autoLoad,boolean deleteEnable,String localVariableName) {
		ChildRelation relation = new ChildRelation();
		relation.localColumn = localColumn;
		relation.foreignColumn = foreignColumn;
		relation.childClass = childClass;
		relation.autoLoad = autoLoad;
		relation.deleteEnable = deleteEnable;
		relation.localVariableName = localVariableName;
		this.childMap.put(childClass.getName(), relation);
	}
	
	/**
	 * 设置当前对象的父对象类型
	 * @param localColumn 当前对象中的关联字段
	 * @param foreignColumn 子对象对象中的关联字段
	 * @param parentClass 父对象的类
	 */
	public void setParent(String localColumn, String foreignColumn,Class parentClass) {
		this.Parent = new ParentRelation();
		this.Parent.localColumn = localColumn;
		this.Parent.foreignColumn = foreignColumn;
		this.Parent.parentClass = parentClass;
	}
	
	
	
	/**
	 * 根据外键关联的模型Class获取对应的外间关联数据的记录
	 * @param beanClass 外间关联对象的Class
	 * @return 包含外间关联数据的一个模型对象
	 */
	public AbstractBean getForignData(Class beanClass,boolean loadChild) {
		AbstractBean forignModel= null;
		try {
			
			if(!this.forignMap.containsKey(beanClass.getName())){
				return forignModel;
			}
			if(this.forignData.containsKey(beanClass.getSimpleName())){
				if(((AbstractBean)this.forignData.get(beanClass.getSimpleName())).size()>0){
					return (AbstractBean) this.forignData.get(beanClass.getSimpleName());
				}
			}
			ForignRelation relation = (ForignRelation) this.forignMap.get(beanClass.getName());
			forignModel =  BeanFactory.LoadBean(beanClass);
			forignModel.loadItem(relation.foreignColumn, this.get(relation.localColumn));
			if(loadChild){
				forignModel.loadAllChildren();
			}
			if(Utils.IsNullOrEmpty(relation.displayKey)){
				this.forignData.put(beanClass.getSimpleName(), (T) forignModel);
				this.set("forignData", forignData);
			}
			else{
				this.set(relation.displayKey, forignModel);
			}
			
			
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
		}
		
		
		return forignModel;
		
	}
	
	
	public void  loadAllForignData(boolean loadChild) {
		try {
			Object[] keys = this.forignMap.keySet().toArray();
			for(int i=0;i<keys.length;i++){
				Object key = keys[i];
				getForignData(Class.forName(key.toString()),loadChild);
			}
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
		}
		
	}
	
	/**
	 * 通过子对象的类型获取与当前对象关联的子对象（表）数据
	 * @param childClass 需要检索的子对象的类
	 * @return 包含对应字表记录的里列表
	 */
	public List<T> getChild(Class childClass) {
		
		//ArrayList<AbstractBean> childList = new ArrayList<AbstractBean>();
		List<T> childList = new ArrayList<T>();
		SqlFilter filter = new SqlFilter();
		try {
			String orderBy=null;
			if(!this.childMap.containsKey(childClass.getName())){
				return childList;
			}
			if(this.childrenData.containsKey(childClass.getSimpleName())){
				if(this.childrenData.get(childClass.getSimpleName()).size()>0){
					return this.childrenData.get(childClass.getSimpleName());
				}
			}
			ChildRelation relation = (ChildRelation) this.childMap.get(childClass.getName());
			if(this.isNew() || get(relation.localColumn) == null ){
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,-1);
			}
			else{
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,get(relation.localColumn));
			}
			
			
			AbstractBean  child =  (AbstractBean) Class.forName(childClass.getName()).newInstance();
			if(child.PrimaryKey!=null && !"".equals(child.PrimaryKey)){
				orderBy = " order by "+child.PrimaryKey +" asc" ;
			}
			childList = BeanFactory.GetBeanList(childClass, filter,orderBy,null,this.connection);

			for (int i = 0; i < childList.size(); i++) {
				AbstractBean bean = ((AbstractBean)childList.get(i));
				bean.set(AbstractBean.KEY_VALUE,bean.getKeyValue());
				bean.set(AbstractBean.DATA_ROW_STATE, AbstractBean.NO_CHANGE);
				bean.connection = this.connection;
				bean.parentNode = this;
			}
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
		}
		this.childrenData.put(childClass.getSimpleName(), childList);
		this.set("childrenData", childrenData);
		return childList;
	}
	
/*	public void initChildRelaction() throws IllegalArgumentException, IllegalAccessException{
		if(this.declareFields == null){
			this.declareFields =this.getClass().getDeclaredFields();
		}
		if(declareFields!=null){
			for(int i=0;i<declareFields.length;i++){
				java.lang.reflect.Field field = declareFields[i];
				field.setAccessible(true);
				One2many o2m = field.getAnnotation(One2many.class);
				if(o2m== null ) continue;
				List<AbstractBean> localVariable = (List<AbstractBean>)field.get(this);	
				this.addChild(o2m.parentColumn()
							, o2m.childColumn()
							, o2m.childClass()
							, o2m.autoLoad()
							, localVariable);
			}
		}
	}
	

	
	public void initMany2oneRelaction() throws IllegalArgumentException, IllegalAccessException{
		if(this.declareFields == null){
			this.declareFields =this.getClass().getDeclaredFields();
		}
		
		if(declareFields!=null){
			for(int i=0;i<declareFields.length;i++){
				java.lang.reflect.Field field = declareFields[i];
				field.setAccessible(true);
				Many2one m2o = field.getAnnotation(Many2one.class);
				if(m2o== null ) continue;
				List<AbstractBean> localVariable = (List<AbstractBean>)field.get(this);
				this.addForignRelation( m2o.localColumn(), 
										m2o.foreignColumn(), 
										m2o.forignClass(),
										m2o.loadChild(),
										m2o.autoLoad(),
										localVariable );
			}
		}
	}
	*/
	
	public void initTableName() throws IllegalArgumentException, IllegalAccessException{
		if(Utils.IsNullOrEmpty(this.TABLE_NAME)){
			Entity entity = this.getClass().getAnnotation(Entity.class);
			this.TABLE_NAME = entity.tableName();
			this.deleteForbidden = entity.deleteForbidden();
		}
	}
	
	public void initPrimaryKey() throws IllegalArgumentException, IllegalAccessException{
		if(Utils.IsNullOrEmpty(this.PrimaryKey)){
			PrimaryKey primaryKey = this.getClass().getAnnotation(PrimaryKey.class);
			this.PrimaryKey = primaryKey.name();
			if("".equals(this.PrimaryKeyField)){
				if(!primaryKey.alias().equals("") ){
					this.PrimaryKeyField =primaryKey.alias();
				}
				else{
					this.PrimaryKeyField =this.PrimaryKey;
				}
				 
			}
			this.AutoIncrease = primaryKey.autoIncrement();
			
		}
	}
	
	public void fillDeclareFieldsFromBean() throws Exception{
		if(this.declareFields == null){
			this.declareFields =this.getClass().getDeclaredFields();
		}
		if(declareFields!=null){
			for(int i=0;i<declareFields.length;i++){
				java.lang.reflect.Field field = declareFields[i];
				field.setAccessible(true);
				Field column = field.getAnnotation(Field.class);
				if(column  == null || Utils.IsNullOrEmpty(column.name())) 
					continue;
				field.set(this, this.get(column.name()));
			}
		}
		
	}
	
	public void fillBeanFromDeclareFields() throws Exception{
		if(this.declareFields == null){
			this.declareFields =this.getClass().getDeclaredFields();
		}
		if(declareFields!=null){
			for(int i=0;i<declareFields.length;i++){
				java.lang.reflect.Field field = declareFields[i];
				field.setAccessible(true);
				Field column = field.getAnnotation(Field.class);
				if(column  == null || Utils.IsNullOrEmpty(column.name())) 
					continue;
				Object value = field.get(this);
				if(!Utils.IsNullOrEmpty(value)){
					this.set(column.name(), value);
				}
			}
		}
		
	}
	
	
	public void loadDeclareChild() throws Exception{
		initDeclareColumns();
		Object[] keys = this.childMap.keySet().toArray();
		for (int i = 0; i < keys.length; i++) {
			Object key = keys[i];
			ChildRelation rel = this.childMap.get(key);
			if(rel.autoLoad && !Utils.IsNullOrEmpty(rel.localVariableName)){
				List<T> childList = getChild(Class.forName(key.toString()));
				for (int j = 0; j < childList.size(); j++) {
					((AbstractBean)childList.get(j)).loadDeclareChild();
				}
				this.getClass().getField(rel.localVariableName).setAccessible(true);
				this.getClass().getField(rel.localVariableName).set(this, childList);
			}

		}
	}
	
	
	/**
	 * 通过子对象的类型获取与当前对象关联的子对象（表）数据
	 * @param childClass 需要检索的子对象的类
	 * @param force2Reload 是否强制从数据库中加载当前子表数据
	 * @return 包含对应字表记录的里列表
	 */
	public List<T> getChild(Class childClass,boolean force2Reload) {
		if(force2Reload){
			this.childrenData.remove(childClass.getSimpleName());
		}
		return this.getChild(childClass);
	}
	
	/**
	 * 通过主键在内存中搜索某个字表记录
	 * @param childClass 子表的模型Class
	 * @param key 主键字段
	 * @return
	 */
	public T fetchChild(Class childClass,Object key){
		T  bean = null;
		if(this.childMap.containsKey(childClass.getName())){
			List<T>childList = this.getChild(childClass);
			for(int i=0;i<childList.size();i++){
				AbstractBean item = (AbstractBean) childList.get(i);
				if(item.getKeyValue().equals(key)){
					item.parentNode = this;
					return childList.get(i);
				}
			}
		}
		else{
			Object[] keys = this.childMap.keySet().toArray();
			for(int i=0;i<keys.length;i++){
				ChildRelation rel = this.childMap.get(keys[i]);
				List<T>childList = this.getChild(rel.childClass);
				for(int j=0;j<childList.size();j++){
					bean = ((AbstractBean<T>)childList.get(j)).fetchChild(childClass, key);
					if(bean!=null){
						return childList.get(j);
					}
						
				}
			}
		}
		return bean;
	}
	
	/**
	 * 从内存中根据模型的class和key移除一条记录（当前记录保存后不会真的从数据库中删除）
	 * @param childClass 要移除的对象的模型的Class
	 * @param key 要移除的对象的key值
	 * @return 被移除的对象
	 */
	public AbstractBean removeRow(Class childClass,Object key){
		AbstractBean bean = (AbstractBean)this.fetchChild(childClass, key);
		if(bean!=null && bean.parentNode!=null){
			bean.getChild(childClass).remove(bean);
		}
		return bean;
	}
	
	/**
	 * 从内存中移除一一个对象
	 * @param bean 要移除的对象
	 */
	public void removeRow(AbstractBean bean){
		bean = (AbstractBean)this.fetchChild(bean.getClass(), bean.getKeyValue());
		if(bean!=null && bean.parentNode!=null){
			bean.getChild(bean.getClass()).remove(bean);
		}
	}
	
	/**
	 * 从内存中根据模型的class和key把一条记录标记为删除（当前对象Save后会真实的从数据库中删除）
	 * @param childClass
	 * @param key
	 * @return 当前被删除的记录对象
	 */
	public T deleteRow(Class childClass,Object key){
		AbstractBean bean = (AbstractBean)this.fetchChild(childClass, key);
		if(bean!=null && bean.parentNode!=null){
			bean.set(AbstractBean.DATA_ROW_STATE, AbstractBean.DELETED);
		}
		return (T) bean;
	}
	
	
	/**
	 * 通过主键在内存中搜索某个字表记录
	 * @param childClass  子表的模型Class
	 * @param field 用来搜索的字段名称
	 * @param value 字段的值
	 * @return
	 */
	public T fetchChild(Class<T> childClass,String field,Object value){
		T bean = null;
		if(this.childMap.containsKey(childClass.getName())){
			List<T>childList = this.getChild(childClass);
			for(int i=0;i<childList.size();i++){
				String strValue = value==null?"":value+"";
				if(((AbstractBean)childList.get(i)).getStringValue(field).equals(strValue)){
					return childList.get(i);
				}
			}
		}
		else{
			Object[] keys = this.childMap.keySet().toArray();
			for(int i=0;i<keys.length;i++){
				ChildRelation rel = this.childMap.get(keys[i]);
				List<T>childList = this.getChild(rel.childClass);
				for(int j=0;j<childList.size();j++){
					//bean = ((AbstractBean)childList.get(j)).fetchChild(childClass,field, value);
					bean = (T) ((AbstractBean)childList.get(i)).fetchChild(childClass, field,value);
					if(bean!=null){
						return bean;
					}
						
				}
				
			}
		}
		return bean;
	}

	/**
	 * 通过子对象的类型获取与当前对象关联的子对象（表）数据
	 * @param childClass 需要检索的子对象的类
	 * @param orderBy 记录排序的规则
	 * @return 包含对应字表记录的里列表
	 * @throws Exception
	 */
	public List<T> getChild(Class<T> childClass, String orderBy)  {
		List<T> childList = new ArrayList<T>();
		SqlFilter filter = new SqlFilter();
		BeanFactory factory = null;
		try {
			if(this.childrenData.containsKey(childClass.getSimpleName())){
				if(this.childrenData.get(childClass.getSimpleName()).size()>0){
					return this.childrenData.get(childClass.getSimpleName());
				}
			}
			
			AbstractBean<T> childBean = (AbstractBean<T>) Class.forName(childClass.getName()).newInstance();
			factory = BeanFactory.GenerateFactory(childBean, this.connection);
			ChildRelation relation = (ChildRelation) this.childMap.get(childClass.getName());
			if(this.isNew() || get(relation.localColumn ) == null ){
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,-1);
			}
			else{
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,get(relation.localColumn));
			}
			
			//filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,get(relation.localColumn));
			
			Entity entity = childClass.getAnnotation(Entity.class);
			if(entity.useInnerQueryMethod()){
				childList = childBean.getBeanList(filter, orderBy);
			}
			else{
				childList = factory.getBeanList(filter, orderBy);
			}
			

			for (int i = 0; i < childList.size(); i++) {
				AbstractBean bean = (AbstractBean )childList.get(i);
				bean.set(AbstractBean.KEY_VALUE,bean.getKeyValue());
				bean.set(AbstractBean.DATA_ROW_STATE, AbstractBean.NO_CHANGE);
				bean.connection = this.connection;
				bean.parentNode = this;
			}
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
		}
		this.childrenData.put(childClass.getSimpleName(), childList);
		this.set("childrenData", childrenData);
		return childList;
	}
	
	public List<T>  getChild(Class<T> childClass, String orderBy,boolean force2reload)  {
		List<T> childList = new ArrayList<T>();
		SqlFilter filter = new SqlFilter();
		BeanFactory factory = null;
		try {
			if(!force2reload && this.childrenData.containsKey(childClass.getSimpleName())){
				if(this.childrenData.get(childClass.getSimpleName()).size()>0){
					return this.childrenData.get(childClass.getSimpleName());
				}
			}
			
			AbstractBean childBean = (AbstractBean) Class.forName(
					childClass.getName()).newInstance();
			factory = BeanFactory.GenerateFactory(childBean, this.connection);
			ChildRelation relation = (ChildRelation) this.childMap.get(childClass.getName());
			if(this.isNew() || get(relation.localColumn ) == null ){
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,-1);
			}
			else{
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,get(relation.localColumn));
			}
			
			//filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,get(relation.localColumn));
			childList = factory.getBeanList(filter, orderBy);

			for (int i = 0; i < childList.size(); i++) {
				AbstractBean bean = (AbstractBean)childList.get(i);
				bean.set(AbstractBean.KEY_VALUE,bean.getKeyValue());
				bean.set(AbstractBean.DATA_ROW_STATE, AbstractBean.NO_CHANGE);
				bean.connection = this.connection;
				bean.parentNode = this;
			}
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
		}
		this.childrenData.put(childClass.getSimpleName(), childList);
		this.set("childrenData", childrenData);
		return childList;
	}
	
	/**
	 * 通过子对象的类型获取与当前对象关联的子对象（表）数据
	 * @param childClass 需要检索的子对象的类
	 * @param ft 包含过滤条件的SqlFilter对象
	 * @param orderBy 记录排序的规则
	 * @return 包含对应字表记录的里列表
	 */
	
	public List<T> getChild(Class<T> childClass,SqlFilter ft, String orderBy)  {
		List<T> childList = new ArrayList<T>();
		SqlFilter filter = new SqlFilter();
		BeanFactory factory = null;
		try {
			if(this.childrenData.containsKey(childClass.getSimpleName())){
				if(this.childrenData.get(childClass.getSimpleName()).size()>0){
					return this.childrenData.get(childClass.getSimpleName());
				}
			}
			
			AbstractBean childBean = (AbstractBean) Class.forName(
					childClass.getName()).newInstance();
			factory = BeanFactory.GenerateFactory(childBean, this.connection);
			ChildRelation relation = (ChildRelation) this.childMap.get(childClass.getName());
			if(this.isNew() || get(relation.localColumn ) == null ){
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,-1);
			}
			else{
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,get(relation.localColumn));
			}
			filter.addFilter(ft, false);
			//filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,get(relation.localColumn));
			childList = factory.getBeanList(filter, orderBy);

			for (int i = 0; i < childList.size(); i++) {
				AbstractBean bean = (AbstractBean)childList.get(i);
				bean.set(AbstractBean.KEY_VALUE,bean.getKeyValue());
				bean.set(AbstractBean.DATA_ROW_STATE, AbstractBean.NO_CHANGE);
				bean.connection = this.connection;
				bean.parentNode = this;
			}
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
		}
		this.childrenData.put(childClass.getSimpleName(), childList);
		this.set("childrenData", childrenData);
		return childList;

	}
	
	/**
	 * 通过子对象的类型获取与当前对象关联的满足指定过滤条件子对象（表）数据
	 * @param childClass 需要检索的子对象的类
	 * @param ft 需要进行过滤的条件（该条件会叠加在原有的关联关系查询条件上）
	 * @return 包含对应字表记录的里列表
	 * @throws Exception
	 */
	public List<T> getChild(Class childClass,SqlFilter ft )  {
		List<T> childList = new ArrayList<T>();
		SqlFilter filter = new SqlFilter();
		try {
			if(this.childrenData.containsKey(childClass.getSimpleName())){
				if(this.childrenData.get(childClass.getSimpleName()).size()>0){
					return this.childrenData.get(childClass.getSimpleName());
				}
			}
			ChildRelation relation = (ChildRelation) this.childMap.get(childClass.getName());
			if(this.isNew() || get(relation.localColumn) == null ){
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,-1);
			}
			else{
				filter.addFilter(relation.foreignColumn, SqlFilter.OP.EQUALS,get(relation.localColumn));
			}
			filter.addFilter(ft, false);
			String orderBy="";
			AbstractBean  child =  (AbstractBean) Class.forName(childClass.getName()).newInstance();
			if(child.PrimaryKey!=null && !"".equals(child.PrimaryKey)){
				orderBy = " order by "+child.PrimaryKey +" asc" ;
			}
			
			childList = BeanFactory.GetBeanList(childClass, filter, orderBy, "");
			
			for (int i = 0; i < childList.size(); i++) {
				AbstractBean bean = (AbstractBean)childList.get(i);
				bean.parentNode = this;
				bean.connection = this.connection;
			}
			this.childrenData.put(childClass.getSimpleName(), childList);
			this.set("childrenData", childrenData);
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
		}
		return childList;
	}
	
	/**
	 * 通过子对象的类型获取与当前对象关联的满足指定过滤条件子对象（表）数据
	 * @param childClass 需要检索的子对象的类
	 * @param filter 需要进行过滤的条件（该条件会叠加在原有的关联关系查询条件上）
	 * @param force2Reload 是否强制从数据库中加载数据
	 * @return 包含对应字表记录的里列表
	 * @throws Exception
	 */
	public List<T> getChild(Class<T> childClass,SqlFilter filter,boolean force2Reload )  {
		if(force2Reload){
			this.childrenData.remove(childClass.getSimpleName());
		}
		return this.getChild(childClass, filter);
	}
	/**
	 * 加载与当前对象关联的所有子对象（表）的数据
	 * 加载后的记录保存在childrenData中
	 * @throws Exception
	 */
	public void  loadAllChildren() throws Exception {
		try {
			Object[] keys = this.childMap.keySet().toArray();
			for (int i = 0; i < keys.length; i++) {
				Object key = keys[i];
				ChildRelation rel = this.childMap.get(key);
				if (rel.autoLoad) {
					List<T> childList = getChild(Class.forName(key.toString()));
					for (int j = 0; j < childList.size(); j++) {
						((AbstractBean)childList.get(j)).loadAllChildren();
					}
				}

			}
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
			throw ex;
		}
		
	}
	

	
	/**
	 * 通过主键加载一条记录
	 * @param key 记录的主键
	 * @return 成功返回true否则返回false
	 * @throws Exception
	 */
	public boolean loadItem(Object key) throws Exception {
		boolean success = false;
		SqlFilter filter = new SqlFilter();
		AbstractBean item = null;
		this.initTableName();
		this.initPrimaryKey();
		this.initDeclareColumns();
		
		if (!this.PrimaryKey.equals("")) {
			try {
				filter.addFilter(this.PrimaryKey, SqlFilter.OP.EQUALS, key);
				if (this.connection == null) {
					this.connection = Utils.GetOpenedConnection();
				}
				List list = BeanFactory.GetBeanList(this.getClass(), filter,null,this.connection);
				if ((list != null) && (list.size() > 0)) {
					item = (AbstractBean) list.get(0);
					if (this.Field.length == 0) {
						this.Field = ((String[]) item.Field.clone());
					}
					
					Object[] keys =item.keySet().toArray();
					for (int i = 0; i < keys.length; ++i) {
						String field = keys[i].toString();
						Object value = item.get(field);
						set(field, value);
					}
					this.childrenData =item.childrenData;
					this.afterLoad();
					set(AbstractBean.KEY_VALUE, item.getKeyValue());
					success = true;
				}
				
				
				

			} catch (Exception ex) {
				ex.printStackTrace();
				throw ex;
			}
		}
		return success;
	}

	/**
	 * 通过制定一个字段的值获取满足条件的一条记录
	 * @param field 用来进行检索的字段
	 * @param value 字段的值
	 * @return 成功返回true否则返回false
	 * @throws Exception
	 */
	public boolean loadItem(String field,Object value) throws Exception {
		boolean success = false;
		SqlFilter filter = new SqlFilter();
		AbstractBean item = null;

		try {
			
			
			filter.addFilter(field, SqlFilter.OP.EQUALS, value);
			if (this.connection == null) {
				this.connection = Utils.GetOpenedConnection();
			}
			
			BeanFactory factory = BeanFactory.GenerateFactory(this.connection);
			factory.connection = this.connection;
			if(PrimaryKey!= null && !"".equals(PrimaryKey)){
				factory.orderBy = " order by "+this.PrimaryKey+" desc ";
			}
			List<T> list  =factory.getBeanList(this.getClass(), filter, 0, 1);
			
			if ((list != null) && (list.size() > 0)) {
				item = (AbstractBean) list.get(0);
				if (this.Field.length == 0) {
					this.Field = ((String[]) item.Field.clone());
				}
				Object[] keys =item.keySet().toArray();
				for (int i = 0; i < keys.length; ++i) {
					String key = keys[i].toString();
					Object val = item.get(key);
					set(key, val);
				}
				set(AbstractBean.KEY_VALUE, item.getKeyValue());
				success = true;
			}
			
			fillDeclareFieldsFromBean();
			//afterLoad();

		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		return success;
	}
	
	public void afterLoad() throws Exception{
		//替换自定义枚举
		/*for(int i=0;i<this.enumList.size();i++){
			 FieldEnum e = enumList.get(i);
			 Object value = this.recursionGetValue(this, e.getField(), 0);
			 Object text = e.getMap().get( value );
			 this.set(e.getDisplayField(),text );
		}*/
		
		//按照配置格式化显示时间字段
		for(int i=0;i<this.timeList.size();i++){
			 TimeFieldFormat e = timeList.get(i);
			 Object value = this.recursionGetValue(this, e.getField(), 0);
			 if(value!= null && !"".equals(value)){
				 Object text = TimeStampToInt.timeToFormate(value+"", e.getFromFormat(),e.getTargetFormat());
				 String fieldName = e.getDisplayField();
				 this.getClass().getField(fieldName).set(this, text);
				 this.set(fieldName,text );
			 }
			 
		}
		
		//自动加载autoLoad=true的外键关联数据
		Object[] keys = this.forignMap.keySet().toArray();
		for(int i=0;i<keys.length;i++){
			Object key = keys[i];
			ForignRelation rel = this.forignMap.get(key);
			if(rel.autoLoad){
				this.getForignData(rel.forignClass, rel.loadChild);
			}
		}
	
		
		//加载从表数据
		loadDeclareChild();
		
		//填充定义的字段
		fillDeclareFieldsFromBean();
		
	}
	
	
	/**
	 * 通过制定一个过滤条件来获取满足条件的第一条记录
	 * @param filter 用来进行过滤的条件
	 * @return 成功返回true否则返回false
	 * @throws Exception
	 */
	public boolean loadFirst(SqlFilter filter) throws Exception {
		boolean success = false;
		AbstractBean item = null;

			try {
				
				if (this.connection == null) {
					this.connection = Utils.GetOpenedConnection();
				}
				BeanFactory factory = BeanFactory.GenerateFactory();
				factory.connection = this.connection;
				
				if(PrimaryKey!= null && !"".equals(PrimaryKey)){
					factory.orderBy = " order by "+this.PrimaryKey+" desc ";
				}
				
				
				List<T> list =null;
				Entity entity = this.getClass().getAnnotation(Entity.class);
				
				if(entity.useInnerQueryMethod()){
					list = this.getBeanList(filter, 0, 1);
				}
				else{
					list  =factory.getBeanList(this.getClass(), filter, 0, 1);
				}
				
				if ((list != null) && (list.size() > 0)) {
					item = (AbstractBean) list.get(0);
					if (this.Field.length == 0) {
						this.Field = ((String[]) item.Field.clone());
					}
					Object[] keys =item.keySet().toArray();
					for (int i = 0; i < keys.length; ++i) {
						String field = keys[i].toString();
						Object value = item.get(field);
						set(field, value);
					}
					set(AbstractBean.KEY_VALUE, item.getKeyValue());
					afterLoad();
					success = true;
				}

			} catch (Exception ex) {
				ex.printStackTrace();
				throw ex;
			}
		
		return success;
	}
	

	
	/**
	 * 把当前对象插入数据库
	 * @return 成功返回true否则返回false
	 * @throws Exception
	 */
	public Boolean insertItem() throws  Exception {
		BeanFactory factory = null;
		String spit = "";
		String insertFields = "";
		String insertValues = "";
		String sql = "";
		List<String> lstField = new ArrayList<String>();
		List<Object> lstValue = new ArrayList<Object>();
		PreparedStatement pst = null;
		
		if(this.connection ==  null){
			this.connection = Utils.GetOpenedWriteConnection();
		}
		if ((this.size() == 0) && (this.connection == null))
			return Boolean.valueOf(false);
		Hashtable<?, ?> columnTypeNames = this.getColumnTypeNames();
		factory = BeanFactory.GenerateFactory(this, this.connection);
		for (int index = 0; index < getFieldCount(); ++index) {
			String field = getField(index);
			if(!this.containsKey(field)) 
				continue;
			
			Object value = get(field);
			spit = (insertFields.equals("")) ? "" : ",";
			if(!columnTypeNames.containsKey(field)) 
				continue;
			field = "`" + field + "`";
			if ((this.PrimaryKey.equals(field)) && (this.AutoIncrease))
				continue;
			if ((value == null) || ("".equals(value)))
				continue;
			
			insertFields = insertFields + spit + field;
			insertValues = insertValues + spit + "?";
			lstField.add(field);
			lstValue.add(value);
		}

		sql = "INSERT INTO " + this.TABLE_NAME + " ( " + insertFields
				+ " ) VALUES (" + insertValues + ")";
		pst = factory.prepareSql(sql, lstField, lstValue, 1);

		pst.executeUpdate();

		ResultSet rsKey = pst.getGeneratedKeys();

		if (rsKey.next()) {
			int key = rsKey.getInt(1);
			if(this.PrimaryKeyField!=null && !"".equals(PrimaryKeyField)){
				set(this.PrimaryKeyField, Integer.valueOf(key));
			}
			else{
				set(this.PrimaryKey, Integer.valueOf(key));
			}
			
		}
		rsKey.close();

		return true;
	}
	
	public void prepareInsertItem() throws  Exception {
		String spit = "";
		String insertFields = "";
		String insertValues = "";
		String sql = "";
		List<String> lstField = new ArrayList<String>();
		List<Object> lstValue = new ArrayList<Object>();
		
		
		if(this.connection ==  null){
			this.connection = Utils.GetOpenedWriteConnection();
		}
		
		if ((this.size() == 0) && (this.connection == null))
			return ;
		Hashtable<?, ?> columnTypeNames = this.getColumnTypeNames();
		BeanFactory factory = BeanFactory.GenerateFactory(this, this.connection);
		for (int index = 0; index < getFieldCount(); ++index) {
			String field = getField(index);
			if(!this.containsKey(field)) 
				continue;
			
			Object value = get(field);
			spit = (insertFields.equals("")) ? "" : ",";
			if(!columnTypeNames.containsKey(field)) 
				continue;
			field = "`" + field + "`";
			if ((this.PrimaryKey.equals(field)) && (this.AutoIncrease))
				continue;
			/*if ((value == null) || ("".equals(value)))
				continue;*/
			
			
			insertFields = insertFields + spit + field;
			insertValues = insertValues + spit + "?";
			lstField.add(field);
			lstValue.add(value);
		}

		sql = "INSERT INTO " + this.TABLE_NAME + " ( " + insertFields
				+ " ) VALUES (" + insertValues + ")";
		if(this.batchPret == null){
			this.batchPret  = this.connection.prepareStatement(sql);
		}
		factory.prepareSql(sql, lstField, lstValue, this.batchPret);
	}

	
	/**
	 * 删除当前对象的数据，同时会级联删除所有与之关联的子表记录
	 * @throws Exception
	 */
	
	public void deleteItem() throws Exception {
		if(this.deleteForbidden){
			throw new CustomerExecption("-100", "Record is forbidden to be deleted!");
		}
		deleteChild();
		deleteSelf();
	}
	
	/**
	 * 删除所有当前对象关联的字表记录
	 * @throws Exception
	 */
	public void deleteChild() throws Exception {
		Iterator keys = this.childMap.keySet().iterator();
		while (keys.hasNext()) {
			String className = (String) keys.next();
			ChildRelation relation = (ChildRelation) this.childMap.get(className);
			if(!relation.deleteEnable) continue;
			List childList = getChild(relation.childClass);
			if (childList == null)
				return;
			for (int i = 0; i < childList.size(); ++i) {
				AbstractBean child = (AbstractBean) childList.get(i);
				if (child.realonly) continue;
				child.connection = this.connection;
				child.deleteItem();
			}
		}
	}
	/**
	 * 删除当前对象对应的数据库记录
	 * @return 成功返回true，否则返回false
	 * @throws Exception
	 */
	public Boolean deleteSelf() throws Exception {
		String condition = "";
		String sql = "";
		Object value = null;
		List<String> lstField = new ArrayList<String>();
		List lstValue = new ArrayList();
		PreparedStatement pst = null;
		BeanFactory factory = null;
		try {
			if(connection == null){
				connection = Utils.GetOpenedWriteConnection();
			}
			if (this.size() > 0 && connection != null) {
				factory = BeanFactory.GenerateFactory(this, connection);
				condition = this.PrimaryKey + "=?";
				sql = "DELETE FROM " + TABLE_NAME + " WHERE " + condition;
				lstField.add(this.PrimaryKey);
				//lstValue.add(this.get(this.PrimaryKey));
				lstValue.add(this.getKeyValue());

				pst = factory.prepareSql(sql, lstField, lstValue);
				pst.executeUpdate();
				pst.close();

				return true;
			}
		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
			throw ex;
		}
		return false;

	}
	
	/**
	 * 把当前对象中的数据update到数据库中
	 * @return  成功返回true否则返回false
	 * @throws Exception
	 */
	public Boolean updateItem() throws Exception {
		BeanFactory factory = null;
		String spit1 = "";
		String updateFields = "";
		String condition = "";
		String sql = "";
		List<String> lstField = new ArrayList<String>();
		List<Object> lstValue = new ArrayList<Object>();
	
		PreparedStatement pst = null;
		Hashtable<?, ?> columnTypeNames = this.getColumnTypeNames();
		if(this.connection ==  null){
			this.connection = Utils.GetOpenedWriteConnection();
		}
		
		if ((this.size() == 0) || (this.Field == null)
				|| (this.connection == null))
			return Boolean.valueOf(false);

		factory = BeanFactory.GenerateFactory(this, this.connection);
		for (int i = 0; i < this.Field.length; ++i) {
			spit1 = (updateFields.equals("")) ? "" : ",";
			
			if (!(this.containsKey(this.Field[i])))
				continue;
			
			if ((this.Field[i] == "") 
					|| (this.Field[i].equals(this.PrimaryKey)) 
					|| readonlyList.contains(this.Field[i]))
				continue;
			String field = this.Field[i];
			Object value = get(field);
			if(!columnTypeNames.containsKey(field)) 
				continue;
			String typeName = (String) columnTypeNames.get(field);

			field = "`" + field + "`";
			if ("".equals(value) || "null".equals(""+value)) {
				value = null;
			}
			updateFields = updateFields + spit1 + field + "=" + "?";
			lstField.add(field);
			lstValue.add(value);
		}

		condition = this.PrimaryKey + "=?";

		sql = "UPDATE " + this.TABLE_NAME + " set " + updateFields + " WHERE "
				+ condition;
	
		lstField.add(this.PrimaryKey);
		//lstValue.add(get(this.PrimaryKey));
		lstValue.add(this.getKeyValue());
		pst = factory.prepareSql(sql, lstField, lstValue);

		pst.executeUpdate();

		pst.close();

		return Boolean.valueOf(true);
	}
	
	/**
	 * 获取当前对象中数据字段的类型列表
	 * @return 一个以当前对象关联的表的字段为键，字段类型名称为值的哈希表
	 */
	protected Hashtable<String, String> getColumnTypeNames() {
		Statement pst = null;
		ResultSet rs = null;
		Hashtable map = new Hashtable();

		String sql = "";
		try {

			if (BeanFactory.ColumnTypeNameDirectory
					.containsKey(this.TABLE_NAME)) {
				map = (Hashtable) BeanFactory.ColumnTypeNameDirectory
						.get(this.TABLE_NAME);
				return map;
			}

			sql = this.getEmptySql();
			pst = this.connection.createStatement();
			rs = pst.executeQuery(sql);
			ResultSetMetaData met = rs.getMetaData();

			for (int i = 0; i < met.getColumnCount(); ++i) {
				String column = met.getColumnName(i + 1);
				String typeName = met.getColumnTypeName(i + 1);
				map.put(column, typeName);
			}
			BeanFactory.ColumnTypeNameDirectory.put(this.TABLE_NAME, map);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (pst != null)
					pst.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	/**
	 * 对当前对象进行序列化，用于网络传输
	 * @return 当前对象序列化后的一个utf8编码的字符串
	 */
	public String serializable() {
		ByteArrayOutputStream byteArrayOutputStream = null;
		ObjectOutputStream objectOutputStream = null;
		String serStr = "";
		try {
			byteArrayOutputStream = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			this.connection = null;
			objectOutputStream.writeObject(this);
			serStr = byteArrayOutputStream.toString("ISO-8859-1");
			serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		try{
			objectOutputStream.close();
			byteArrayOutputStream.close();
		}catch(Exception e){}
		
		return serStr;
	}
	
	/**
	 * 把json格式的数据填充到当前的对象中（只填当前对象中存在的键，忽略不存在的键）
	 * 会递归填充与当前对象的类关联的字对象
	 * @param jsonString json格式的字符串
	 */
	public void json2Model(String jsonString) {
		try {
			JSONObject jsonObj = JSONObject.fromObject(jsonString);
			if (jsonObj != null) {
				json2Model(jsonObj);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * 把json格式的数据填充到当前的对象中（只填当前对象中存在的键，忽略不存在的键）
	 * 会递归填充与当前对象的类关联的字对象
	 * @param jsonObj 包含数据信息的json对象
	 */
	public void json2Model(JSONObject jsonObj) {
		try {
			if (jsonObj != null) {
				// 填充主表
				Object [] fields = jsonObj.keySet().toArray();
				for (int i = 0; i < fields.length; i++) {
					String field = fields[i].toString();
					if (jsonObj.containsKey(field)) {
						Object value = jsonObj.get(field);
						if (value != null && value.equals(null)) {
							this.set(field, null);
						} else {
							this.set(field, value);
						}
					}
				}
				// 填充从表
				if (jsonObj.containsKey("childrenData")
						&& jsonObj.getJSONObject("childrenData") != null) {
					JSONObject children = jsonObj.getJSONObject("childrenData");
					Object[] keys = this.childMap.keySet().toArray();
					for (int i = 0; i < keys.length; i++) {
						ChildRelation relation = this.childMap.get(keys[i]);
						Class beanClass = Class.forName(keys[i].toString());
						String shortClsName = beanClass.getSimpleName();
						if (children.containsKey(shortClsName)) {
							JSONArray arr = children.getJSONArray(shortClsName);
							List<T> beanList = BeanFactory.GetBeanList(beanClass, arr,this.connection);
							this.childrenData.put(shortClsName, beanList);
							for (int j = 0; j < beanList.size(); j++) {
								((AbstractBean<T>)beanList.get(j)).json2Model(arr.getJSONObject(j));
								((AbstractBean<T>)beanList.get(j)).parentNode =this;
							}
							if(!Utils.IsNullOrEmpty(relation.localVariableName)){
								this.getClass().getField(relation.localVariableName).set(this, beanList);
							}
							//this.childMap.get
							
						}
					}
				}

			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void batchExecute() throws SQLException{
		if(this.batchPret!=null && this.connection!=null){
			this.batchPret.executeBatch();
			this.batchPret = null;
		}
	}
	/**
	 * 把当前对象转成json的字符串
	 * @return 包含当前对象字段内容的json字符串
	 */
	public String toJson(){
		String strJson="";
		
		for (int i = 0; i < this.Field.length; ++i){
			String key = this.Field[i];
			String value = this.getStringValue(key);
			value = value.replace("\r\n", "{chr(13)}").replace("'", "`");
			value = value.replace("\t", "{chr(14)}");
			value = Utils.HtmlSpecialChars(value);
			String spit = strJson == "" ? "" : ",";
			strJson +=spit+ "\""+ key +"\":\""+value+"\"";
    	}
		
		if(!"".equals(strJson)){
			strJson = "{" + strJson + "}";
		}
		
		return strJson;
	}
	
		
	
	/**
	 * 根据指定的对象类型查询符合过滤条件和分页信息检查询对象列表
	 * @param beanClass 需要进行检索的对象Class
	 * @param filter 过滤条件
	 * @param page 分页信息
	 * @return 指定类型的对象列表
	 */
	public abstract <T>List<T> getBeanList(SqlFilter filter, PageInfo page);
	
	
	/**
	 * 根据指定的对象类型查询条件和记录的开始索引，结束索引检查询对象列表
	 * @param beanClass 需要进行检索的对象类型
	 * @param filter 过滤条件
	 * @param startIndex 记录的开始索引
	 * @param endIndex 记录的结束索引
	 * @return 指定类型的对象列表
	 */
	public abstract <T>List<T> getBeanList(SqlFilter filter, int startIndex, int endIndex);
	
	
	/**
	 * 根据过滤条件和排序字段列表返回查询结果
	 * @param filter 过滤条件
	 * @param orderBy 排序字段列表，多个字段间用逗号分隔
	 * @return 指定类型的对象列表
	 */
	public abstract <T>List<T> getBeanList(SqlFilter filter, String orderBy);
	
	
	/**
	 * 根据制定的对象类型查询符合条件的对象列表
	 * @param beanClass 需要进行查询的对象的Class 
	 * @param filter filter 查询条件
	 * @param selectColumns 需要显示的字段列表，如果有多个用逗号分隔，如果该值为null则显示所有字段
	 * @param orderBy 排序规则 order by ....
	 * @param con 数据库连接（如果该参数为空框架会调用默认的数据库连接）
	 * @return 符合查询条件的beanClass类型的对象列表 
	 * @throws Exception 
	 */
	public abstract <T> List<T> getBeanList(SqlFilter filter,String orderBy,String selectColumns) throws Exception;


}

